<template>
  <div>
    <div class="data">
      <el-form :inline="true" :moodel="params" style="margin-left: 10px">
        <el-form-item label="名称">
          <el-input
            v-model="params.name"
            placeholder="按名称查找"
            class="select"
          >
          </el-input>
        </el-form-item>
        <el-form-item style="margin-left: 33px; margin-top: 15px">
          <el-button icon="el-icon-search" type="primary" @click="getList(1)"
            >查询</el-button
          >
          <el-button icon="el-icon-plus" type="success" @click="add"
            >新增</el-button
          >
          <el-button icon="el-icon-delete" type="danger" @click="removeMore"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="rows"
        stripe
        style="width: 100%"
        @selection-change="SelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="img" label="图片" width="180">
          <template slot-scope="scope">
            <img
              style="width: 40px; height: 40px"
              v-if="scope.row.img"
              :src="scope.row.img"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="id"
          label="类别"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="level"
          label="层级"
          width="180"
        ></el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" style="margin-right:15px" @click="edit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除此数据吗？" @confirm="remove(scope.row)">
            <el-button icon="el-icon-delete" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChange"
        @current-change="getList"
        :current-page="params.pageNum"
        :page-sizes="[5, 10, 20, 100, 200, 300, 400]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog :title="form._id ? '编辑' : '新增'" :visible.sync="dialogFormVisible" width="400px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="图片" prop="img">
          <upload
            action="/upload"
            :cicle="false"
            :width="300"
            :height="300"
            :on-success="onSuccess">
            <img style="max-width:100%;max-height:100%;" v-if="form.img" :src="form.img" class="avatar">
            <div v-else style="border:1px dashed #e4e4e4;width:100px;height:100px;line-height:100px;text-align:center;"><i class="el-icon-plus avatar-uploader-icon"></i></div>
          </upload>
          <!-- <div class="image" @click="openFile">
            <img style="max-width: 100%; max-height: 100%;" v-if="form.img" :src="form.img" />
            <span v-else>+</span>
          </div>
          <input style="display:none" ref="file" multiple accept="image/*" type="file" @change="changeFile"> -->
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="id">
          <el-select v-model="form.id" placeholder="请选择">
            <el-option
              v-for="id in Ids"
              :key="id.value"
              :label="id.label"
              :value="id.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumbmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import Upload from '../../components/Upload.vue';
export default {
  name: "shangpinSort",
  components: {Upload},
  data() {
    return {
      //查询参数
      params: {
        name:'',
        pageNum: 1,
        pageSize: 5,
      },
      rows: [],
      total: 0,
      dialogFormVisible: false,
      form: {
        _id: 0,
        img: '',
        name: '',
      },
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        img: [{ required: true, message: "图片不能为空", trigger: "blur" }],
      },
      Ids: [
        {label:'新品',value:'365D33795BD04D3984F2ABBF356F59C3'},
        {label:'高端定制',value:'E735768C2EB844E3AD087D5A3F5B4042'},
        {label:'展厅现货',value:'8C4B983238934202ACEF22CBFBEB6C44'},
        {label:'CGLDG系列',value:'365D33795BD04D3984F2ABBF356F59C3_6E2C14E8DC7E41E686CB867F000ACAC5'},
        {label:'BZDZLLY系列',value:'365D33795BD04D3984F2ABBF356F59C3_31070FD670554E22A6DA5A3D05BC5799'},
        {label:'意式极简',value:'E735768C2EB844E3AD087D5A3F5B4042_7521EC0B928344AB8B97954BD0C2A972'},
        {label:'现代极简',value:'8C4B983238934202ACEF22CBFBEB6C44_56DD8609BB5C431892F1FDF37DCF2357'},
        {label:'轻奢家居',value:'E735768C2EB844E3AD087D5A3F5B4042_78B69C8EB2A94B7BA4A0176236D0AF69'},
      ],
      selecteds: [],
    };
  },
  methods: {
    //获取列表
    getList(pageNum) {
      if (pageNum) this.params.pageNum = pageNum;
      this.$http({
        url: "/admin/sort",
        params: this.params,
      }).then((res) => {
        this.total = res.total;
        this.rows = res.rows;
      });
    },
    //修改pageSize
    sizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageNum = 1;
      this.getList();
    },
    //新增
    add() {
      //初始化
      this.form = {
        _id: 0,
        img: '',
        name:''
      }
      this.dialogFormVisible = true;
    },
    //修改
    edit(row){
      this.form = row
      this.dialogFormVisible = true;
    },
    //删除
    remove(row){
      this.$http({
        url: '/admin/sort',
        method:'DELETE',
        params: {sortId:row._id},
      }).then((res) => {
        if (!res.errorMsg) {
          this.getList(1)
        }
      })
    },
    SelectionChange(rows) {
      //存储选中的数据
      this.selecteds = rows;
    },
    //批量删除
    removeMore(){
      //获取选中的数据
      let checkedRowsPromise = []
      let success = [], fail = []
      for(let i = 0; i < this.selecteds.length; i ++){
        checkedRowsPromise.push(
          new Promise(resovle => {
            let row = this.selecteds[i]
            this.$http({
              url: '/admin/sort',
              method:'DELETE',
              params: {sortId:row._id},
            }).then((res) => {
              if (!res.errorMsg) {
                success.push(row._id)
              }else{
                fail.push(row._id)
              }
              resovle()
            })
          })
        )
      }
      this.$confirm('此操作将删除选中的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //删除
        Promise.all(checkedRowsPromise).then(() => {
          this.$message({
            message:`批量删除完成，成功删除${success.length}条数据，删除失败${fail.length}条数据`,
            duration:3000
          });
          this.getList(1)
        })
      })
    },
    // openFile(){
    //   let fileElement = this.$refs.file
    //   fileElement.click()
    // },
    // changeFile(e){
    //   let files = e.target.files
    //   let formData = new FormData()
    //   formData.append('file',files[0])

    //   this.$http({
    //     url: '/upload',
    //     method: 'POST',
    //     data: formData
    //   }).then((res) => {
    //     console.log(res)
    //     if(res.filename) this.form.img = api.baseURL + '/uploads/' + res.filename
    //   })
    // },
    onSuccess(res){
      //拼装图片路径赋值给表单
      if(res.filename) this.form.img = api.baseURL + '/uploads/' + res.filename
    },
    sumbmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.sortId = this.form._id
          this.$http({
            url: '/admin/sort',
            method:this.form.sortId ? 'PUT' : 'POST',//通过sortId判断是新增还是修改
            data: this.form,
          }).then((res) => {
            if (!res.errorMsg) {
              this.dialogFormVisible = false;
              this.getList(this.form.sortId ? undefined : 1);
            }
          })
        }
      });
    },
  },
  created() {
    this.getList();
  },
  mounted() {},
};
</script>

<style>
.select {
  width: 160px;
  height: 40px;
  font-size: 15px;
  color: #e9e9e9;
  margin-top: 14px;
}
.image {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  text-align: center;
  line-height: 100px;
  font-size: 28px;
}
</style>